import { FastifyRequest } from 'fastify';
import requestIp from 'request-ip';

export const getReqMainInfo: (req: FastifyRequest) => {
  [prop: string]: any;
} = (req) => {
  const { query, headers, method, body, connection } = req;

  const { remoteAddress } = connection || {};
  let ip = req.id || remoteAddress;
  if (!ip) ip = requestIp.getClientIp(req)!;

  let user: any;

  if ('user' in req) {
    const { id, realname } = req.user as SC.User.Info;
    user = { id, realname };
  }

  return {
    user,
    url: req.originalUrl || req.url,
    host: headers.host,
    ip,
    method,
    query,
    body,
    scid: headers?.scid,
  };
};
